package com.cusi.config;

import com.alibaba.fastjson.JSONObject;
import com.cusi.pojo.User;
import com.cusi.service.UserServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;


public class UserRealm  extends AuthorizingRealm {

    public static final String SESSION_USER_PERMISSION = "userInfo";

    @Autowired
    UserServiceImpl userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getSession().getAttribute(UserRealm.SESSION_USER_PERMISSION);
      // User user =(User)subject.getSession().getAttribute(UserRealm.SESSION_USER_PERMISSION);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(user));
        //设置当前用户的权限
        System.out.println(jsonObject.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions((Collection<String>) jsonObject.get("permissionsList"));
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        String username = (String) token.getPrincipal();
        String password = String.valueOf((char[])token.getCredentials());
        //连接数据库
        User user = userService.queryInfo(username, password);
        //JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(user).toString());
        if (null == user){
            return null;
        }
        SecurityUtils.getSubject().getSession().setAttribute(UserRealm.SESSION_USER_PERMISSION,user);
        //MD5加密， MD5盐值加密
        //密码认证，shiro来做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
